<template>
  <el-card class="purchase-records-card" shadow="never">
    <template #header>
      <div class="card-header">
        <span>采购记录</span>
        <el-button type="primary" @click="exportRecords">导出记录</el-button>
      </div>
    </template>
    
    <!-- 筛选条件 -->
    <el-form :model="filterParams" :inline="true" class="filter-form">
      <el-form-item label="供应商">
        <el-select v-model="filterParams.supplierId" placeholder="请选择供应商" clearable class="form-item-width">
          <el-option
            v-for="supplier in suppliers"
            :key="supplier.id"
            :label="supplier.name"
            :value="supplier.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="时间范围">
        <el-date-picker
          v-model="filterParams.dateRange"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="loadPurchaseRecords">查询</el-button>
        <el-button @click="resetFilter">重置</el-button>
      </el-form-item>
    </el-form>
    
    <!-- 智能提醒 -->
    <PurchaseSmartAlerts 
      :purchase-records="purchaseRecords"
      @alert-click="handleAlertClick"
    />
    
    <!-- 采购记录列表 -->
    <AdvancedTable
      :data="purchaseRecords"
      :columns="recordColumns"
      :loading="loading"
      :pagination="paginationConfig"
      row-key="id"
      show-toolbar
      show-refresh
      show-pagination
      @refresh="loadPurchaseRecords"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <template #totalAmount="{ row }">
        ¥{{ row.totalAmount.toLocaleString() }}
      </template>
      
      <template #invoiceStatus="{ row }">
        <el-tag v-if="row.invoiceStatus === 'pending'">待开票</el-tag>
        <el-tag v-else-if="row.invoiceStatus === 'received'" type="success">已收票</el-tag>
        <el-tag v-else-if="row.invoiceStatus === 'uploaded'" type="warning">已上传</el-tag>
        <span v-else>-</span>
      </template>
      
      <template #actions="{ row }">
        <el-button size="small" @click="viewRecordDetail(row)">详情</el-button>
      </template>
    </AdvancedTable>
  </el-card>
  
  <!-- 采购记录详情对话框 -->
  <el-dialog
    v-model="detailDialogVisible"
    title="采购记录详情"
    width="800px"
  >
    <el-descriptions :column="2" border v-if="currentRecord && currentRecord.id">
      <el-descriptions-item label="入库单号">{{ currentRecord.inboundNumber }}</el-descriptions-item>
      <el-descriptions-item label="供应商">{{ currentRecord.supplier?.name }}</el-descriptions-item>
      <el-descriptions-item label="入库日期">{{ currentRecord.inboundDate }}</el-descriptions-item>
      <el-descriptions-item label="总金额">¥{{ currentRecord.totalAmount.toLocaleString() }}</el-descriptions-item>
      <el-descriptions-item label="是否含票">{{ currentRecord.hasInvoice ? '是' : '否' }}</el-descriptions-item>
      <el-descriptions-item label="发票状态">{{ getInvoiceStatusText(currentRecord.invoiceStatus) }}</el-descriptions-item>
      <el-descriptions-item label="运费">¥{{ currentRecord.freight.toLocaleString() }}</el-descriptions-item>
      <el-descriptions-item label="备注">{{ currentRecord.remark }}</el-descriptions-item>
    </el-descriptions>
    
    <!-- 商品明细 -->
    <el-table :data="currentRecord.items || []" style="margin-top: 20px" border v-if="currentRecord && currentRecord.id">
      <el-table-column prop="productName" label="商品名称" />
      <el-table-column prop="specification" label="规格" />
      <el-table-column prop="unit" label="单位" />
      <el-table-column prop="quantity" label="数量" />
      <el-table-column prop="unitPrice" label="单价">
        <template #default="{ row }">
          ¥{{ row.unitPrice.toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column prop="totalPrice" label="总价">
        <template #default="{ row }">
          ¥{{ row.totalPrice.toLocaleString() }}
        </template>
      </el-table-column>
    </el-table>
    
    <template #footer>
      <el-button @click="detailDialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from '@vue/runtime-core'
import { ElMessage } from 'element-plus'
import AdvancedTable from '@/components/AdvancedTable.vue'
import * as procurementAPI from '@/api/procurement'
import PurchaseSmartAlerts from './PurchaseSmartAlerts.vue'

interface PurchaseRecord {
  id: number
  inboundNumber: string
  supplierId: number
  inboundDate: string
  totalAmount: number
  hasInvoice: boolean
  invoiceStatus: string
  freight: number
  remark: string
  createdAt: string
  updatedAt: string
  supplier?: {
    id: number
    name: string
  }
  items?: PurchaseItem[]
}

interface PurchaseItem {
  id: number
  productName: string
  specification: string
  unit: string
  quantity: number
  unitPrice: number
  totalPrice: number
}

interface Supplier {
  id: number
  name: string
}

// 数据状态
const purchaseRecords = ref<PurchaseRecord[]>([])
const suppliers = ref<Supplier[]>([])
const loading = ref(false)
const detailDialogVisible = ref(false)
const currentRecord = ref<PurchaseRecord>({
  id: 0,
  inboundNumber: '',
  supplierId: 0,
  inboundDate: '',
  totalAmount: 0,
  hasInvoice: false,
  invoiceStatus: '',
  freight: 0,
  remark: '',
  createdAt: '',
  updatedAt: ''
})

// 分页配置
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 筛选参数
const filterParams = reactive({
  supplierId: undefined as number | undefined,
  dateRange: [] as string[]
})

// 表格列配置
const recordColumns = computed(() => [
  {
    prop: 'inboundNumber',
    label: '入库单号',
    width: 150,
    fixed: 'left'
  },
  {
    prop: 'supplier.name',
    label: '供应商',
    width: 150
  },
  {
    prop: 'inboundDate',
    label: '入库日期',
    width: 120,
    formatter: (value: string) => value ? value.split('T')[0] : ''
  },
  {
    prop: 'totalAmount',
    label: '总金额',
    width: 120,
    slot: 'totalAmount'
  },
  {
    prop: 'hasInvoice',
    label: '是否含票',
    width: 100,
    formatter: (value: boolean) => value ? '是' : '否'
  },
  {
    prop: 'invoiceStatus',
    label: '发票状态',
    width: 100,
    slot: 'invoiceStatus'
  },
  {
    prop: 'freight',
    label: '运费',
    width: 100,
    formatter: (value: number) => `¥${value.toLocaleString()}`
  },
  {
    prop: 'createdAt',
    label: '创建时间',
    width: 120,
    formatter: (value: string) => value ? value.split('T')[0] : ''
  },
  {
    prop: 'actions',
    label: '操作',
    width: 100,
    fixed: 'right',
    slot: 'actions'
  }
])

// 分页配置
const paginationConfig = computed(() => ({
  currentPage: pagination.page,
  pageSize: pagination.limit,
  total: pagination.total,
  pageSizes: [10, 20, 50, 100],
  layout: 'total, sizes, prev, pager, next, jumper'
}))

// 加载采购记录列表
const loadPurchaseRecords = async () => {
  loading.value = true
  try {
    const params = {
      supplierId: filterParams.supplierId,
      startDate: filterParams.dateRange[0],
      endDate: filterParams.dateRange[1],
      page: pagination.page,
      limit: pagination.limit
    }
    
    // 这里需要创建相应的API接口来获取采购记录
    // 暂时使用模拟数据
    const response = {
      list: [],
      pagination: {
        total: 0,
        page: 1,
        limit: 20
      }
    }
    
    purchaseRecords.value = response.data.list
    pagination.total = response.data.pagination.total
  } catch (error) {
    ElMessage.error('加载采购记录失败: ' + (error as Error).message)
  } finally {
    loading.value = false
  }
}

// 加载供应商列表
const loadSuppliers = async () => {
  try {
    const response = await procurementAPI.getSuppliers({
      page: 1,
      limit: 1000
    })
    suppliers.value = response.data?.list || []
  } catch (error) {
    ElMessage.error('加载供应商列表失败: ' + (error as Error).message)
  }
}

// 查看记录详情
const viewRecordDetail = async (record: PurchaseRecord) => {
  try {
    // 这里需要创建相应的API接口来获取采购记录详情
    // 暂时使用模拟数据
    currentRecord.value = {
      ...record,
      items: [
        {
          id: 1,
          productName: '示例商品1',
          specification: '规格1',
          unit: '件',
          quantity: 10,
          unitPrice: 100,
          totalPrice: 1000
        },
        {
          id: 2,
          productName: '示例商品2',
          specification: '规格2',
          unit: '件',
          quantity: 5,
          unitPrice: 200,
          totalPrice: 1000
        }
      ]
    }
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取记录详情失败: ' + (error as Error).message)
  }
}

// 获取发票状态文本
const getInvoiceStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'pending': '待开票',
    'received': '已收票',
    'uploaded': '已上传'
  }
  return statusMap[status] || '-'
}

// 导出记录
const exportRecords = () => {
  ElMessage.info('导出功能待实现')
}

// 重置筛选条件
const resetFilter = () => {
  Object.assign(filterParams, {
    supplierId: undefined,
    dateRange: []
  })
  loadPurchaseRecords()
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pagination.limit = size
  loadPurchaseRecords()
}

// 处理当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadPurchaseRecords()
}

// 处理智能提醒点击
const handleAlertClick = (alert: any) => {
  ElMessage.info(`处理提醒: ${alert.title}`)
  // 可以根据提醒类型执行不同的操作
  switch (alert.type) {
    case 'delayedDelivery':
      // 可以跳转到延期交货筛选
      ElMessage.info('已筛选显示延期交货记录')
      break
    case 'largeAmount':
      // 可以跳转到大额采购筛选
      ElMessage.info('已筛选显示大额采购记录')
      break
    case 'frequentSupplier':
      // 可以跳转到频繁供应商筛选
      ElMessage.info('已筛选显示频繁供应商记录')
      break
  }
}

// 生命周期
onMounted(() => {
  loadPurchaseRecords()
  loadSuppliers()
})
</script>

<style scoped>
.purchase-records-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-form {
  margin-bottom: 20px;
}

.filter-form .el-form-item {
  margin-right: 20px;
}

.form-item-width {
  width: 200px;
}
</style>
